package com.project651.www;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;

public class JoinGameService extends Service {
	public static final String CLIENTSERVER = ".com.project651.www.JoinGameService";
	static final String TAG = "ClientProcess";
	static final int BUFFERSIZE = 512;
	static final int SERVERPORT = 3333;
	
	Thread client;
	private final IBinder joinGameBinder = new JoinGameServiceBinder();
	
	class JoinGameServiceBinder extends Binder {
		public JoinGameService getService() {
			return JoinGameService.this;
		}
	}
	
	private String serverAddress;
	private Socket socket;
	private InputStream in;
	private OutputStream out;
	boolean isRunning = true;
	
	@Override
	public IBinder onBind(Intent intent) {
		return joinGameBinder;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
	}
	
	public void sendStatus(int gameStatus) {
		try {
			out.write(gameStatus);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void attemptConnection(String addr) {
		serverAddress = addr;
		client = new Thread(clientThread);
		client.start();
	}
	
	private void onReceiveWord(String word) {
		Intent i = new Intent(CLIENTSERVER);
		Bundle b = new Bundle();
		b.putCharSequence("Word", word);
		i.putExtras(b);
		sendBroadcast(i);
	}
	
	private Runnable clientThread = new Runnable() {
		public void run() {
			try {
				socket = new Socket(serverAddress, SERVERPORT);
				in = socket.getInputStream();
				out = socket.getOutputStream();
				isRunning = true;
				byte[] buffer = new byte[BUFFERSIZE];
				
				//send request for game
				out.write(buffer);
				
				boolean gotWord = false;
				while (isRunning) {
					in.read(buffer);
					
					
					onReceiveWord(Crypto.decrypt(buffer));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	};

}
